package org.gurms.common.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.gurms.service.dto.Page;


public class JqueryUtil {
	
	public final static String FLEXIGRID_ID    = "id";
	public final static String FLEXIGRID_CELL  = "cell";
	public final static String FLEXIGRID_ROWS  = "rows";
	public final static String FLEXIGRID_PAGE  = "page";
	public final static String FLEXIGRID_TOTAL = "total";
	
	private JqueryUtil(){		
	}
	
	public static Map createFlexigridJson(Page page, Class type, String idField){
		List<Map> rows = new ArrayList<Map>();
		for(Object tmp: page.getResult()){
			Field[] fields = type.getDeclaredFields();
			int len = fields.length;
			Object[] cell = new Object[len];
			for(int i = 0 ; i < len ; i ++){
				if(ReflectionUtil.isBaseType(fields[i])){
					cell[i] = ReflectionUtil.getFieldValue(tmp, fields[i].getName());
				}
			}
			Object idValue = ReflectionUtil.getFieldValue(tmp, idField);
			Map row = new HashMap();
			row.put(FLEXIGRID_ID, idValue);
			row.put(FLEXIGRID_CELL, cell);
			rows.add(row);
		}
		Map json = new HashMap();
		json.put(FLEXIGRID_PAGE, page.getPageNo());
		json.put(FLEXIGRID_TOTAL, page.getTotalCount());
		json.put(FLEXIGRID_ROWS, rows);

		return json;
	}
}
